package per.hx.bs.config;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author HuXing
 * @date 2018/4/24  22:06
 */
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    private final
    HuXingBsConfig huXingBsConfig;

    private final String jar = ".jar";
    private final String classes = "classes";


    @Autowired
    public WebAppConfig(HuXingBsConfig huXingBsConfig) {
        this.huXingBsConfig = huXingBsConfig;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = huXingBsConfig.getUploadPath();
        if (uploadPath == null || "".equals(uploadPath)) {
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            if (imagesPath.indexOf(jar) > 0) {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            } else if (imagesPath.indexOf(classes) > 0) {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            uploadPath = imagesPath;
        }
        registry.addResourceHandler("/images/**").addResourceLocations("file:/" + uploadPath);
        registry.addResourceHandler("/files/**").addResourceLocations("file:/" + uploadPath);
        super.addResourceHandlers(registry);

    }
}
